<script setup>
import { ref, reactive, markRaw } from 'vue'
const formRenderer = ref({})
const visibleDrawer = ref(false)
const detailsDrawer = ref(false)
import mySelect from './ChannelSelect.vue'
import ImageUpload from './ImageUpload.vue'
import { useUserStore } from '@/stores'
import {
  artGetDetailService,
  artPublishService,
  artEditService
} from '@/api/article'
import { baseURL } from '@/utils/request'
const formModel = ref({})
import quill from './quillEditor.vue'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['success'])
import { formatTime } from '@/utils/format'
const { user } = useUserStore()
const content = reactive([
  {
    type: 'input',
    id: 'title',
    label: '文章标题',
    el: {
      placeholder: '请输入标题'
    },
    rules: [{ required: true, message: '请输入文章标题', trigger: 'blur' }]
  },
  {
    type: 'select',
    id: 'cate_id',
    label: '文章分类',
    component: markRaw(mySelect),
    rules: [{ required: true, message: '请选择文章分类', trigger: 'blur' }]
  },
  {
    id: 'imgData',
    label: '文章封面',
    component: markRaw(ImageUpload),
    rules: [{ required: true, message: '请选择文章封面', trigger: 'blur' }]
  },
  {
    id: 'content',
    label: '文章内容',
    component: markRaw(quill),
    rules: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
  }
])

const open = async (row, show = false) => {
  if (show) {
    detailsDrawer.value = true
  } else {
    visibleDrawer.value = true
  }
  if (row.id) {
    console.log('编辑回显')

    const res = await artGetDetailService(row.id)
    let url = baseURL + res.data.data.cover_img

    let file = await imageUrlToFile(url, res.data.data.cover_img)
    if (file) {
      console.log('File created:', file)
      // 这里你可以使用file对象进行文件上传或其他操作
      formModel.value = {
        ...res.data.data,
        imgData: {
          imgUrl: url,
          cover_img: file
        }
      }
    }
  } else {
    console.log('添加功能')
  }
}
const imageUrlToFile = async (imageUrl, fileName) => {
  try {
    // 使用fetch API获取图片数据
    const response = await fetch(imageUrl)
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    const blob = await response.blob()

    // 创建File对象
    return new File([blob], fileName, { type: blob.type })
  } catch (error) {
    console.error('Error converting imageUrl to File:', error)
    return null
  }
}
// 关闭弹框前的回调
const handleClose = () => {
  formRenderer.value.resetFields && formRenderer.value.resetFields()
  formRenderer.value.getComponentById &&
    formRenderer.value.getComponentById('content').readycontent()

  formModel.value = {}
}

// 发布文章

const onPublish = async (state) => {
  try {
    // 将已发布还是草稿状态，存入 state
    formModel.value.state = state

    // 转换 formData 数据
    const fd = new FormData()
    // 获取图片对象
    let imgData = formModel.value.imgData
    //整理为后台需要的数据
    let newObj = { ...formModel.value, ...imgData }
    let params = Object.keys(newObj)
      .filter((key) => newObj[key])
      .reduce((prev, next) => ({ ...prev, [next]: newObj[next] }), {})
    for (let key in params) {
      fd.append(key, params[key])
    }

    if (formModel.value.id) {
      console.log('编辑操作')
      await artEditService(fd)
      ElMessage.success('编辑成功')
      visibleDrawer.value = false
      emit('success', 'edit')
    } else {
      // 添加请求
      console.log(fd)
      await artPublishService(fd)
      ElMessage.success('添加成功')
      visibleDrawer.value = false
      emit('success', 'add')
    }
  } catch (error) {
    console.log(error)
  }
}
defineExpose({
  open
})
</script>

<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
    @close="handleClose"
  >
    <el-form-renderer
      label-width="100px"
      :content="content"
      ref="formRenderer"
      v-model:FormData="formModel"
    >
      <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
      <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
    </el-form-renderer>
  </el-drawer>
  <!-- 预览 -->
  <el-drawer
    v-model="detailsDrawer"
    direction="rtl"
    size="50%"
    title="预览文章"
    @close="handleClose"
  >
    <div>
      <h2>{{ formModel.title }}</h2>
      <div class="info-box">
        作者：{{ user.nickname }} 发布时间：{{
          formatTime(formModel.pub_date)
        }}
        文章分类:{{ formModel.cate_name }}
      </div>

      <el-image class="" :src="formModel?.imgData?.imgUrl"> </el-image>
      <div v-html="formModel.content"></div>
    </div>
  </el-drawer>
</template>

<style>
.info-box {
  border-bottom: 2px solid #ccc;
  padding-bottom: 10px;
  box-sizing: border-box;
  margin: 20px 0;
}
</style>
